package com.taxx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.taxx.common.Result;
import com.taxx.entity.SysUser;
import com.taxx.entity.TaxIncomeReport;
import com.taxx.entity.TaxIdentityReport;
import com.taxx.entity.TaxPlatformReport;
import com.taxx.mapper.SysUserMapper;
import com.taxx.mapper.TaxIncomeReportMapper;
import com.taxx.mapper.TaxIdentityReportMapper;
import com.taxx.mapper.TaxPlatformReportMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Dashboard控制器
 * 
 * @author taxx
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/dashboard")
public class DashboardController {

    @Autowired
    private TaxIncomeReportMapper taxIncomeReportMapper;

    @Autowired
    private TaxIdentityReportMapper taxIdentityReportMapper;

    @Autowired
    private TaxPlatformReportMapper taxPlatformReportMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 获取统计数据
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getStats() {
        try {
            Map<String, Object> stats = new HashMap<>();
            
            // 统计收入信息数量
            QueryWrapper<TaxIncomeReport> incomeQuery = new QueryWrapper<>();
            incomeQuery.eq("deleted", 0);
            Long incomeCount = taxIncomeReportMapper.selectCount(incomeQuery);
            stats.put("incomeCount", incomeCount);
            
            // 统计身份信息数量
            QueryWrapper<TaxIdentityReport> identityQuery = new QueryWrapper<>();
            identityQuery.eq("deleted", 0);
            Long identityCount = taxIdentityReportMapper.selectCount(identityQuery);
            stats.put("identityCount", identityCount);
            
            // 统计平台信息数量
            QueryWrapper<TaxPlatformReport> platformQuery = new QueryWrapper<>();
            platformQuery.eq("deleted", 0);
            Long platformCount = taxPlatformReportMapper.selectCount(platformQuery);
            stats.put("platformCount", platformCount);
            
            // 统计用户数量
            QueryWrapper<SysUser> userQuery = new QueryWrapper<>();
            userQuery.eq("deleted", 0);
            Long userCount = sysUserMapper.selectCount(userQuery);
            stats.put("userCount", userCount);
            
            log.info("获取统计数据成功：{}", stats);
            return Result.success(stats);
            
        } catch (Exception e) {
            log.error("获取统计数据失败", e);
            return Result.error("获取统计数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取最近活动
     */
    @GetMapping("/activities")
    public Result<List<Map<String, Object>>> getRecentActivities() {
        try {
            List<Map<String, Object>> activities = new java.util.ArrayList<>();
            
            // 获取最近的收入信息导入活动
            QueryWrapper<TaxIncomeReport> incomeQuery = new QueryWrapper<>();
            incomeQuery.eq("deleted", 0)
                      .orderByDesc("create_time")
                      .last("LIMIT 3");
            List<TaxIncomeReport> recentIncome = taxIncomeReportMapper.selectList(incomeQuery);
            
            for (TaxIncomeReport income : recentIncome) {
                Map<String, Object> activity = new HashMap<>();
                activity.put("id", "income_" + income.getId());
                activity.put("content", "导入了收入信息数据");
                activity.put("time", formatDateTime(income.getCreateTime()));
                activity.put("type", "primary");
                activities.add(activity);
            }
            
            // 获取最近的身份信息导入活动
            QueryWrapper<TaxIdentityReport> identityQuery = new QueryWrapper<>();
            identityQuery.eq("deleted", 0)
                        .orderByDesc("create_time")
                        .last("LIMIT 3");
            List<TaxIdentityReport> recentIdentity = taxIdentityReportMapper.selectList(identityQuery);
            
            for (TaxIdentityReport identity : recentIdentity) {
                Map<String, Object> activity = new HashMap<>();
                activity.put("id", "identity_" + identity.getId());
                activity.put("content", "导入了身份信息数据");
                activity.put("time", formatDateTime(identity.getCreateTime()));
                activity.put("type", "success");
                activities.add(activity);
            }
            
            // 获取最近的平台信息导入活动
            QueryWrapper<TaxPlatformReport> platformQuery = new QueryWrapper<>();
            platformQuery.eq("deleted", 0)
                        .orderByDesc("create_time")
                        .last("LIMIT 3");
            List<TaxPlatformReport> recentPlatform = taxPlatformReportMapper.selectList(platformQuery);
            
            for (TaxPlatformReport platform : recentPlatform) {
                Map<String, Object> activity = new HashMap<>();
                activity.put("id", "platform_" + platform.getId());
                activity.put("content", "导入了平台信息数据");
                activity.put("time", formatDateTime(platform.getCreateTime()));
                activity.put("type", "warning");
                activities.add(activity);
            }
            
            // 按时间排序，取前10条
            activities.sort((a, b) -> {
                String timeA = (String) a.get("time");
                String timeB = (String) b.get("time");
                return timeB.compareTo(timeA);
            });
            
            if (activities.size() > 10) {
                activities = activities.subList(0, 10);
            }
            
            log.info("获取最近活动成功，共{}条", activities.size());
            return Result.success(activities);
            
        } catch (Exception e) {
            log.error("获取最近活动失败", e);
            return Result.error("获取最近活动失败：" + e.getMessage());
        }
    }

    /**
     * 获取系统信息
     */
    @GetMapping("/system-info")
    public Result<Map<String, Object>> getSystemInfo() {
        try {
            Map<String, Object> systemInfo = new HashMap<>();
            
            // 系统启动时间（这里使用当前时间作为示例）
            LocalDateTime startTime = LocalDateTime.now().minusHours(2); // 假设系统启动2小时
            systemInfo.put("startTime", formatDateTime(startTime));
            
            // 最后登录时间（这里使用当前时间作为示例）
            LocalDateTime lastLoginTime = LocalDateTime.now().minusMinutes(30); // 假设30分钟前登录
            systemInfo.put("lastLoginTime", formatDateTime(lastLoginTime));
            
            // 系统版本
            systemInfo.put("version", "v1.0.0");
            
            // 系统状态
            systemInfo.put("status", "正常运行");
            
            log.info("获取系统信息成功：{}", systemInfo);
            return Result.success(systemInfo);
            
        } catch (Exception e) {
            log.error("获取系统信息失败", e);
            return Result.error("获取系统信息失败：" + e.getMessage());
        }
    }

    /**
     * 格式化日期时间
     */
    private String formatDateTime(LocalDateTime dateTime) {
        if (dateTime == null) {
            return "未知时间";
        }
        return dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }
}
